<template>
  <div style="width: 100%;">
    <h2>投诉建议处理</h2>
    <div v-if="isLoading">加载中...</div>
    <el-table v-else :data="currentPageData" stripe style="width: 100%">
      <el-table-column prop="id" label="记录id"></el-table-column>
      <el-table-column prop="type" label="记录类型"></el-table-column>
      <el-table-column prop="communityId" label="所属小区id"></el-table-column>
      <el-table-column prop="ownerId" label="业主id"></el-table-column>
      <el-table-column prop="complainContent" label="投诉/建议内容"></el-table-column>
      <el-table-column label="附件">
        <template #default="scope">
          <el-button v-if="scope.row.attachment" type="text" @click="downloadFile(scope.row.attachment)">下载附件</el-button>
          <span v-else>无附件</span>
        </template>
      </el-table-column>
      <el-table-column prop="complainDate" label="投诉/建议时间"></el-table-column>
      <el-table-column prop="processingStatus" label="处理状态"></el-table-column>
      <el-table-column prop="measure" label="整改措施"></el-table-column>
      <el-table-column prop="handlerId" label="处理人员id"></el-table-column>
      <el-table-column prop="completionDate" label="处理完成时间"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" v-if="scope.row.processingStatus === '待处理'" @click="handleComplaint(scope.row)">处理</el-button>
          <el-button size="small" v-if="scope.row.processingStatus === '处理中'" @click="openFeedbackDialog(scope.row)">反馈</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination-component"
    >
    </el-pagination>

    <el-dialog v-model="feedbackDialogVisible" title="投诉/建议整改反馈">
      <el-form ref="editFormRef" v-model="feedbackForm">
        <el-form-item label="整改措施">
          <el-input type="textarea" v-model="feedbackForm.measure" placeholder="请输入整改措施"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="feedbackDialogVisible = false">取消</el-button>
        <el-button @click="submitFeedback">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";

const token = localStorage.token;
const headers = { Authorization: token };

const isLoading = ref(false);
const complaintList = ref([]);
const feedbackDialogVisible = ref(false);
const feedbackForm = ref({
  complainId: null,
  status: '',
  measure: ''
});

const currentFeedbackComplaint = ref(null);
const dataLoaded = ref(false);
const editFormRef = ref(null);

// 分页相关变量
const currentPage = ref(1);
const pageSize = ref(10);
const total = computed(() => complaintList.value.length);

// 当前页数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return complaintList.value.slice(start, end);
});

const getComplaints = async () => {
  isLoading.value = true;
  try {
    const response = await axios.get('/api/complain/property', { headers });
    if (response.data.code === 200) {
      complaintList.value = response.data.data;
      dataLoaded.value = true;
    } else {
      ElMessage.error('获取投诉建议列表失败');
    }
  } catch (error) {
    console.log('获取投诉建议列表失败:', error);
    ElMessage.error(`获取投诉建议列表失败：${error.message}`);
  } finally {
    isLoading.value = false;
  }
};

const openFeedbackDialog = (row) => {
  if (dataLoaded.value) {
    feedbackDialogVisible.value = true;
    currentFeedbackComplaint.value = row;
    feedbackForm.value = { measure: "" };
  } else {
    console.log('数据尚未加载完成，无法打开反馈对话框');
  }
};

const submitFeedback = async () => {
  if (!String(feedbackForm.value.measure).trim()) {
    ElMessage.warning('请输入整改措施');
    return;
  }

  if (!currentFeedbackComplaint.value ||!currentFeedbackComplaint.value.id) {
    ElMessage.error('未找到有效的投诉记录 ID');
    return;
  }

  try {
    const response = await axios.put('/api/complain/property/update/', null, {
      headers,
      params: {
        complainId: currentFeedbackComplaint.value.id,
        status: '已完成',
        measure: feedbackForm.value.measure
      }
    });

    if (response.data.code === 200) {
      const index = complaintList.value.findIndex(
          (item) => item.id === currentFeedbackComplaint.value.id
      );

      if (index!== -1) {
        complaintList.value[index].processingStatus = "已完成";
        complaintList.value[index].measure = feedbackForm.value.measure;
        complaintList.value[index].completionDate = new Date().toISOString();
      }

      feedbackDialogVisible.value = false;
      ElMessage.success('投诉反馈提交成功，标记为已完成');
      await getComplaints();
    } else {
      ElMessage.error('提交反馈失败');
    }
  } catch (err) {
    ElMessage.error(`提交反馈失败: ${err.message}`);
  }
};

const handleComplaint = async (complaint) => {
  try {
    const response = await axios.put('/api/complain/property/update/', null, {
      headers,
      params: {
        complainId: complaint.id,
        status: '处理中',
        measure: '已开始处理'
      }
    });

    if (response.data.code === 200) {
      const index = complaintList.value.findIndex(
          (item) => item.id === complaint.id
      );

      if (index!== -1) {
        complaintList.value[index].handlerId = localStorage.getItem('userId');
        complaintList.value[index].processingStatus = "处理中";
        complaintList.value[index].measure = '已开始处理';
        complaintList.value = [...complaintList.value];
      }
      ElMessage.success("已开始处理");
    } else {
      ElMessage.error('处理失败');
    }
  } catch (err) {
    ElMessage.error(`处理失败：${err.message}`);
  }
};

const downloadFile = async (path) => {
  try {
    const response = await axios.get('/api/file', {
      params: {
        path: path
      },
      headers: {
        Authorization: token
      },
      responseType: 'blob'
    });
    const blob = new Blob([response.data], { type: response.headers['content-type'] });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    const contentDisposition = response.headers['content-disposition'];
    a.download = contentDisposition ? contentDisposition.split('filename*=UTF-8\'\'')[1] : 'downloaded_file';
    a.click();
    window.URL.revokeObjectURL(url);
    ElMessage.success('文件下载成功');
  } catch (error) {
    ElMessage.error('文件下载失败：' + error.message);
  }
};

// 处理分页大小改变
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
};

// 处理当前页码改变
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};

onMounted(() => {
  getComplaints();
});
</script>

<style scoped>
.pagination-component {
  margin-top: 10px;
  text-align: center;
}
</style>